package com.stylefeng.guns;

import net.arnx.wmf2svg.gdi.svg.SvgGdi;
import net.arnx.wmf2svg.gdi.wmf.WmfParser;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.freehep.graphicsio.emf.EMFInputStream;
import org.freehep.graphicsio.emf.EMFRenderer;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class WordToHtml {

    public static void main(String[] args) throws Exception {
        final String path = "D:\\data\\附件七、客户开发说明文档\\";
        final String file = "SGIP——中国联通短消息业务设备规范 第三分册：联通在信网关设备规范v2.0.doc";
        final String imagepath = "D:\\image\\";
        InputStream input = new FileInputStream(path + file);
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                File imgPath = new File(imagepath);
                if (!imgPath.exists()) {//图片目录不存在则创建
                    imgPath.mkdirs();
                }
                try {
                    if (suggestedName.contains(".emf")) {
                        InputStream is = new ByteArrayInputStream(content);
                        EMFInputStream emf = new EMFInputStream(is, EMFInputStream.DEFAULT_VERSION);
                        EMFRenderer emfRenderer = new EMFRenderer(emf);
                        final int width = (int) emf.readHeader().getBounds().getWidth();
                        final int height = (int) emf.readHeader().getBounds().getHeight();
                        final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                        Graphics2D g2 = result.createGraphics();
                        emfRenderer.paint(g2);
                        //创建储存图片二进制流的输出流
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        //创建ImageOutputStream流
                        ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
                        //将二进制数据写进ByteArrayOutputStream
                        ImageIO.write(result, "png", imageOutputStream);
                        suggestedName = suggestedName.replace(".emf", ".png");
                        FileUtils.writeByteArrayToFile(new File(imagepath + suggestedName), baos.toByteArray());
                    } else if (suggestedName.contains(".wmf")) {
                        try {
                            InputStream in = new ByteArrayInputStream(content);
                            WmfParser parser = new WmfParser();
                            final SvgGdi gdi = new SvgGdi(false);
                            parser.parse(in, gdi);
                            Document doc = gdi.getDocument();
                            suggestedName = suggestedName.replace(".wmf", ".svg");
                            TransformerFactory factory = TransformerFactory.newInstance();
                            Transformer transformer = factory.newTransformer();
                            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 1.0//EN");
                            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            transformer.transform(new DOMSource(doc), new StreamResult(bos));
                            FileUtils.writeByteArrayToFile(new File(imagepath + suggestedName), bos.toByteArray());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        File file = new File(imagepath + suggestedName);
                        OutputStream os = new FileOutputStream(file);
                        os.write(content);
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "file:///" + imagepath + suggestedName;
            }
        });

        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        outStream.close();
        String content = clearWordFormat(new String(outStream.toByteArray()));
        String[] arr = content.split("</p>");
        int num = arr.length;
        System.out.println("数组长度：" + num);
        String newContent = "";
        int page = 1;
        for (int i = 0; i < num; i++) {
            if(i != 0 && i%20 == 0){
                String a = arr[i];
                if(newContent.lastIndexOf("<table") > 0 && !newContent.substring(newContent.lastIndexOf("<table")).contains("</table>")){
                    if(a.contains("</table>")){
                        newContent += arr[i];
                        newContent += "<p>-------------------------------------------"+page+"-------------------------------------------------</p>";
                        page++;
                    }
                }else if(newContent.lastIndexOf("</table>") > 0 && !newContent.substring(newContent.lastIndexOf("</table>")).contains("<table")){
                    if(a.contains("<table")){
                        newContent += "<p>-------------------------------------------"+page+"-------------------------------------------------</p>";
                        newContent += arr[i];
                        page++;
                    }else{
                        newContent += arr[i];
                        newContent += "<p>-------------------------------------------"+page+"-------------------------------------------------</p>";
                        page++;
                    }
                }else{
                    newContent += arr[i];
                    newContent += "<p>-------------------------------------------"+page+"-------------------------------------------------</p>";
                    page++;
                }
            }else {
                newContent += arr[i];
            }
        }
        FileUtils.writeStringToFile(new File(path, "test.html"), newContent, "utf-8");
    }

    public static String clearWordFormat(String content) {
        //删除不需要的标签
        content = content.replaceAll("<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|[ovwxpOVWXP]:\\w+)[^>]*?>", "");
        //删除不需要的属性
        content = content.replaceAll("<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>", "<$1$2>");
        //删除<STYLE TYPE="text/css"></STYLE>及之间的内容
        int styleBegin = content.indexOf("<style");
        int styleEnd = content.indexOf("</style>") + 8;
        String style = content.substring(styleBegin, styleEnd);
        content = content.replace(style, "");
        //设置所有表格样式
        content = content.replaceAll("<table", "<table border=\"1\"");
        content.replaceAll(" ","");
        content = content.replaceAll("<head>", "<head><script src=\"jquery.min.js\"></script>");
        content = content.replaceAll("</body>", "</body><script src=\"record.js\"></script>");
        return content;
    }

}